<?php

class MessageBoxController
{
    private $followModel;
    private $userStatisticsModel;
    private $messageBoxModel;
    private $autoUidModel;
    private $tokenUserCacheModel;
    private $diaryAttachmentModel;
    private $shopModel;
    private $topicModel;
    private $messageService;

    function __construct()/*{{{*/
    {
    	$this->followModel          =   new FollowModel();
        $this->userStatisticsModel  =   new UserStatisticsModel();
        $this->messageBoxModel      =   new MessageBoxModel();
        $this->autoUidModel         =   new AutoUidModel();
        $this->tokenUserCacheModel  =   new TokenUserCacheModel();
        $this->diaryAttachmentModel =   new DiaryAttachmentModel();
        $this->shopModel            =   new ShopModel();
        $this->topicModel          	=   new TopicModel();
        $this->messageService       =   new MessageService();
    }/*}}}*/

    public function sendMessage($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['mUid']))
        {
            AC::$errorNo    =   'MBC001';
            return  FALSE;
        }
        $tpl = isset($info['tpl']) ? $info['tpl'] : 0;
        // 判断是否是当前登录用户
        if (AC::HOST_UID != $info['uid']){
            AC::$errorNo    =   'UC010';
            return  FALSE;
        }
        
        // 是否禁言
        $status  =  $this->autoUidModel->checkUserStatus(AC::$hostUserBaseInfo);
        if (!empty(AC::$errorNo)){
            return  FALSE;
        }

        $userInfo = $this->autoUidModel->getUserInfo($info['uid']);
        if ($userInfo['level']>5 || $userInfo['is_vip']){
        }else{
            AC::$errorMsg   =   '六级或六级以上才可以发私信哦，请努力达到六级就可以发私信啦';
            AC::$errorNo    =   'AUM015';
            return false;
        }
        
        // 是否拉黑
        $access = $this->checkAccessPremission($info['mUid']);
        if (empty($access)) return  FALSE;
        
        // 接收人信息
        $mUidBaseInfo   =   $this->autoUidModel->getUserInfo($info['mUid']);
        if (!isset($mUidBaseInfo['nickname'])){
            AC::$errorNo    =   'MBC002';
            return  FALSE;
        }
        
        // 发送私信的数据
        $data = array(
                'uid'      =>    $info['uid'],
                'mUid'     =>    $info['mUid'],
                'nickname' =>    AC::$hostUserBaseInfo['nickname'],
                'mNickname'=>    $mUidBaseInfo['nickname'],
                'content'  =>    $info['content'],
                'tpl'      =>    $tpl
        );
        // 分页可能需要
        isset($info['id'])    &&    $data['id']    =    $info['id'];
        
        // 亲加云数据处理，直接返回
        if ($info['go_type']) {
            $tmp = $data;
            $tmp['avatar'] = $mUidBaseInfo['avatar'];
            $tmp['type']   = $this->outboxType;
            $result = $this->returnGoTypeMessageData($tmp);
            return $result;
        }
        
        // 附件判断
        $attachment = FALSE;
        $voice      = FALSE;
        if (is_array($info['attachment'])  &&  count($info['attachment']) > 0){
            $attachment = TRUE;
        }
        if (is_array($info['voice'])  &&  count($info['voice']) >  0){
            $voice = TRUE;
        }
        
        // 处理分享数据
        if (!empty($info['data_action']) && !empty($info['data_title']) && !empty($info['data_content'])){
        
            $topicShareData = $this->topicModel->structureTopicShareData($info);
            if (!empty(AC::$errorNo)) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return  FALSE;
            }
            $data['msgType'] = $topicShareData['msgType'];
            $data['msgData'] = $topicShareData['msgData'];
        }
        
        $result =   $this->messageBoxModel->sendMessage($data, $attachment, $voice);
        //$result =   $this->messageService->sendMessage($data['uid'], $data['mUid'], $data, true, $attachment, $voice);
        if (empty($result)){
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }

        // 存储图片
        $this->addMessageAttachment ($info, $result[0]['last_attachment']);
        unset($result['last_attachment']);
        
        if (isset($info['id'])  &&  ''  === $info['id'])
        {
            $result =   TRUE;
        }
        else
        {
            $result =   $this->getMessageInfo($data);
            if (AC::OPEN_SYNC_SENDMSG_IM_STATUS && AC::$openSendChatMsg2IMVersion){
                $messageService = new MessageService();
                $messageService->sendMsg2UserQueue($info['uid'], $info['mUid'], $result);
            }
        }
        return  $result;
    }/*}}}*/

    private function addMessageAttachment ($info, $type_id) {
        if (AC::$errorNo) return false;

        $info['type']    = 3;
        $info['bodyId']  = 1;
        $info['type_id'] = $type_id;

        $userService = new UserService();
        $user = $userService->getUserInfo($info['uid'], AC::HOST_UID);

        $attachmentService = new AttachmentService();
        $attachmentService->saveDiaryAttachment($info, $user);

        AC::$errorNo = '';
        return true;
    }
    
    private function returnGoTypeMessageData ($param) {
        $data= $this->structureMessageInfoData($param);
        return array($data);
    }
	
    public function getMessageList($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'MBC003';
            return  FALSE;
        }
  
        // 新接口只返回最近的100条[2015.01.07]
        if (isset($info['updateTime']) && $info['updateTime'] == 1){
            $info['start']     =    0;
            $info['length']    =    100;
            
            $result =   $this->messageBoxModel->getMessageList($info);
        }else{
            if (empty($info['listMode'])){
                $result =   $this->messageBoxModel->getMessageList($info);
            }else{
                if ('up' == $info['listMode']){
                    $result =   $this->messageBoxModel->getMessageListUp($info);
                }else{
                    $result =   $this->messageBoxModel->getMessageListDown($info);
                }
            }
        }
        
        if (empty($result)  ||  !is_array($result)) return  $result;
        foreach ($result    as  &$value)
        {
            $tmpUserInfo        =   $this->autoUidModel->getUserInfo($value['mUid']);
            $value['mNickname'] =   $this->autoUidModel->getRemarkName($tmpUserInfo);
            $value['avatar']    =   AC::getProtocolUriByOS($tmpUserInfo['avatar']);
            $value['user']      =   $this->autoUidModel->checkIsMe($tmpUserInfo);
            $value['user']['nickname']  =    $this->autoUidModel->getRemarkName($value['user']);
	    // 获取附件
            $value['attachmentList']    =    array();
            $value['voiceList']         =    array();
            if(intval($value['last_attachment']) > 0){
                $attachment         =   $this->diaryAttachmentModel->getMessageAttachment($value);
                $value['attachment']    =    $attachment['attachment'];
                $value['voiceList']     =    $attachment['voiceList'];
            }
        }

        # clear inbox new times!
        $this->userStatisticsModel->resetMessageStatistics($info);
        return  $result;
    }/*}}}*/

    public function getMessageInfo($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['mUid']))
        {
            AC::$errorNo    =   'MBC001';
            return  FALSE;
        }

        if (empty($info['listMode']))/*{{{*/
        {
            $result =   $this->messageBoxModel->getMessageInfo($info);
        }
        else
        {
            if ('up' == $info['listMode'])
            {
                $result =   $this->messageBoxModel->getMessageInfoUp($info);
            }
            else
            {
                $result =   $this->messageBoxModel->getMessageInfoDown($info);
            }
        }/*}}}*/
        
        if (empty($result)){
            return array();
        }
        
        $data = $tmp = array();
        foreach ($result    as  &$value)
        {
            $tmpUserInfo         =    $this->autoUidModel->getUserInfo($value['mUid']);
            $value['avatar']     =    $tmpUserInfo['avatar'];
            $value['mNickname']  =    $this->autoUidModel->getRemarkName($tmpUserInfo);
            // 获取附件
            $tmp['uid']         =   $value['uid'];
            $tmp['last_attachment']          =   UK::getBodyidByItemid('MC/'. $value['uid'], $value['id']);
            if ( $value['type'] == 1){
                $tmp['uid']         =   $value['mUid'];
                $tmp['last_attachment']      =   UK::getBodyidByItemid('MC/'. $value['mUid'], $value['mid']);
            }
            $value['attachmentList']    =    array();
            $value['voiceList']         =    array();
            if ($tmp['last_attachment']){
                $attachment         =   $this->diaryAttachmentModel->getMessageAttachment($tmp);
                if ($attachment['attachment'] || $attachment['voiceList']){
                    $value['attachment']    =    $attachment['attachment'];
                    $value['voiceList']     =    $attachment['voiceList'];
                }
            }
            isset($info['tpl']) && $value['tpl'] = $info['tpl'];
            $tmp  = $this->structureMessageInfoData($value);
            $data[] =  $tmp;
        }

        $this->resetUserUnReadNum($info['uid'], $info['mUid']);
        return  $data;
    }/*}}}*/
    
    private function structureMessageReq ($param) {
        $data = array(
            'id'           =>    $param['id'],
            'uid'          =>    $param['uid'],
            'mUid'         =>    $param['mUid'],
            'mNickname'    =>    $param['mNickname'],
            'avatar'       =>    $param['avatar'],
            'type'         =>    2,
            'content'      =>    $param['content']
        );
        
        return $data;
    }
    
    private function structureMessageInfoData($param){
        $data = array(
              'id'           =>    '0',
              'uid'          =>    '0',
              'mUid'         =>    '0',
              'mNickname'    =>    '',
              'avatar'       =>    '',
              'type'         =>    '',
              'msgType'      =>    '',
              'content'      =>    '',
              'time'         =>    AC::SERVER_TIME,
              'status'       =>    '0',
              'data'         =>    (Object) array(),
              'attachment'   =>    array(),
              'voiceList'    =>    array(),
        );
        
        isset($param['id'])           &&    $data['id']           =    strval($param['id']);
        isset($param['uid'])          &&    $data['uid']          =    strval($param['uid']);
        isset($param['mUid'])         &&    $data['mUid']         =    strval($param['mUid']);
        isset($param['mNickname'])    &&    $data['mNickname']    =    strval($param['mNickname']);
        isset($param['avatar'])       &&    $data['avatar']       =    strval($param['avatar']);
        isset($param['type'])         &&    $data['type']         =    strval($param['type']);
        isset($param['msgType'])      &&    $data['msgType']      =    strval($param['msgType']);
        isset($param['content'])      &&    $data['content']      =    strval($param['content']);
        isset($param['time'])         &&    $data['time']         =    strval($param['time']);
        isset($param['status'])       &&    $data['status']       =    strval($param['status']);
        isset($param['attachment'])   &&    $data['attachment']   =    $param['attachment'];
        isset($param['voiceList'])    &&    $data['voiceList']    =    $param['voiceList'];
        // 匹配查找表情
        $emotionData = Emotion::matchEmotionDetail($data['content']);
        if ($emotionData && $emotionData['id'] > 0){
            $emotionInfo = $this->shopModel->getGoodsDetailByGoodsType($emotionData['id'], 1, 'Shop-Emotion');
            if ($emotionInfo){
                $data['msgType'] = $param['msgType'] = 'emotion';
                $msgData = array(
                        'eid'    =>    $emotionInfo['id'],
                        'etitle' =>    $emotionInfo['name'],
                        'eicon'  =>    $emotionInfo['cover_s'],
                        'image'  =>    $emotionData['image']
                );
                isset($param['tpl']) && $msgData['tpl'] = $param['tpl'];
                $param['msgData'] = json_encode($msgData);
            }
        }
        
        // 私信返回附加媒体信息
        $data['data'] = $this->shopModel->restructMsgData($param['msgType'], $param['msgData']);
        
        // 附件支持,升级提示
        $tipsAttachment = $data['attachment'];
        if (!empty($data['voiceList'])){
            $tipsAttachment = $data['voiceList'];
        }
        $data['content'] = UK::tipsUpgrade($tipsAttachment, $data['content'], 'attachment');
        return $data;
    }
    
    public function getMessageInbox($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'MBC003';
            return  FALSE;
        }

        $result =   $this->messageBoxModel->getMessageInbox($info);
        
        // 获取附件
        if (!empty($result)){
            foreach ($result as $value ){
                $tmp['uid']                 =    $value['mUid'];
                $tmp['last_attachment']     =    UK::getBodyidByItemid('MC/'. $value['mUid'], $value['id']);
                $attachment                 =    $this->diaryAttachmentModel->getMessageAttachment($tmp);
                $value['attachment']        =    $attachment['attachment'];
                $value['voiceList']         =    $attachment['voiceList'];
            }
        }

        # clear inbox new times!
        $this->userStatisticsModel->resetMessageStatistics($info);
        return  $result;
    }/*}}}*/

    public function getMessageOutbox($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'MBC004';
            return  FALSE;
        }

        $result =   $this->messageBoxModel->getMessageOutbox($info);
        
        // 获取附件
        if (!empty($result)){
            foreach ($result as $value ){
                $tmp['uid']                 =    $value['uid'];
                $tmp['last_attachment']     =    UK::getBodyidByItemid('MC/'. $value['uid'], $value['id']);
                $attachment                 =    $this->diaryAttachmentModel->getMessageAttachment($tmp);
                $value['attachment']        =    $attachment['attachment'];
                $value['voiceList']         =    $attachment['voiceList'];
            }
        }
        
        return  $result;
    }/*}}}*/

    public function removeMessage($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'MBC003';
            return  FALSE;
        }
        if (empty($info['mUid']) &&  empty($info['id']))
        {
            AC::$errorNo    =   'MBC004';
            return  FALSE;
        }
        
        // 删除私信时,删除私信附件
        $tmp['uid']      =    $info['uid'];
        $tmp['id']       =    UK::getBodyidByItemid('MC/'. $info['uid'], $info['id']);
        if (!empty($tmp['uid']) && !empty($tmp['id'])){
            $attachment      =    $this->diaryAttachmentModel->removeMessageAttachment($tmp);
        }

//        $this->resetUserUnReadNum($info['uid'], $info['mUid']);

        $result =   $this->messageBoxModel->removeMessage($info);
        if (empty($result)) return false;

        return  true;
    }/*}}}*/

    private function resetUserUnReadNum($uid, $mUid)
    {
        if (empty($uid) || empty($mUid))
        {
            return false;
        }

        $listInfo   =   $this->messageBoxModel->getMessageListInfo(array('uid' => $uid, 'mUid' => $mUid));
        if ($listInfo)
        {
//            $userService = new UserService();
//            $userService->updateUserStatistics($uid, array('messageTimes' => - abs($listInfo['unReadNum'])));
            return $this->messageBoxModel->resetUnReadNum(array('uid' => $uid, 'mUid' => $mUid));
        }

        return false;
    }
	
    private function checkAccessPremission($uid)/*{{{*/
    {
    	if ((AC::HOST_UID   ==  $uid))  return  TRUE;
    
    	$array      =   array('uid' => AC::HOST_UID, 'fUid' => $uid, 'alarm' => TRUE);
    	$isBlackMe  =   $this->followModel->isBlackMe($array);
    	if (empty($isBlackMe))  return  TRUE;
    
    	return  FALSE;
    }/*}}}*/

    public function getEmotionList($param)
    {
        $uid = isset($param['uid']) ? intval($param['uid']) : 0;
        $content = isset($param['content']) ? $param['content'] : '';
        if($uid < 1) {
            AC::$errorNo = "MBC004";
            return false;
        }
        if(empty($content)) {
            AC::$errorNo = "MBC005";
            return false;
        }
        $paper_emotion_ids_mebuy = array();
        if (empty(AC::$iosFullVersion)) {
            // 获取我已购买的全部信纸、表情
            $paper_emotion_ids_mebuy = $this->shopModel->getShopIdListMeBuy($uid);

        }

        $imageList  = Emotion::emotionToImgList($content, $paper_emotion_ids_mebuy);
        $content   = Emotion::emotionToMark($content, $paper_emotion_ids_mebuy);

        return ['content' => $content, 'imageList' => $imageList];
    }

}


